import { onBeforeUnmount, onMounted, ref } from 'vue';

const useFormatTime = () => {
  const year = ref('');
  const currentTime = ref(''); // 新增一个响应式变量用于存储当前时间

  const formatTime = (n: number) => {
    return n < 10 ? `0${n}` : `${n}`;
  };

  const updateTime = () => {
    const date = new Date();
    const yearValue = formatTime(date.getFullYear());
    const month = formatTime(date.getMonth() + 1);
    const day = formatTime(date.getDate());
    const hour = formatTime(date.getHours());
    const minute = formatTime(date.getMinutes());
    const second = formatTime(date.getSeconds());

    year.value = `${yearValue}年${month}月${day}日`; // 更新年份
    currentTime.value = `${hour}:${minute}:${second}`; // 更新时间
  };

  const timer = ref<NodeJS.Timeout | null>(null);

  onMounted(() => {
    updateTime(); // 初始化时立即更新一次时间
    timer.value = setInterval(updateTime, 1000); // 每秒更新时间
  });

  onBeforeUnmount(() => {
    if (timer.value) {
      clearInterval(timer.value); // 清除定时器
    }
  });

  return {
    year,
    currentTime // 返回响应式的时间变量
  };
};

export default useFormatTime;
